package juc.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @ClassName : SpinLockDemo
 * @Author : hyy
 * @Date: 2020-03-11
 *
 *题目：实现一个自旋锁
 *自旋锁的好处：循环比较获取直至获取成功为止，没有类似wait的阻塞
 *通过CAS操作完成自旋锁，A线程先进来调用myLock方法自己持有3秒钟，B随后进来发现
 *当前有其他前程持有锁，不是null.所以只能通过自选等待，直到A释放锁后B随之抢到
 *
 */
public class SpinLockDemo {
    AtomicReference<Thread> atomicReference = new AtomicReference<Thread>();

    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "\t 进入方法，尝试获取锁");
        while (!atomicReference.compareAndSet(null, thread)) {

        }
        System.out.println(thread.getName() + "\t 获取锁");

    }

    public void MyUnLock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "\t 即将释放锁");
        while (!atomicReference.compareAndSet(thread, null)) {
        }

    }

    public static void main(String[] args) throws InterruptedException {
        SpinLockDemo spinLockDemo = new SpinLockDemo();

        new Thread(() -> {
            try {
                spinLockDemo.myLock();
                TimeUnit.SECONDS.sleep(5);
                spinLockDemo.MyUnLock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1").start();
        // 让t1线程先获取锁
        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> {
            spinLockDemo.myLock();
            spinLockDemo.MyUnLock();
        }, "t2").start();
    }
}
